<template>
  <div style="height:6vh;padding:10px 20px;background-color:#fff;">
    <span style="line-height:60px;font-size:20px;">文章资料</span>
    <el-button type="primary" @click="addNews()"
               style="float: right;margin-top:10px;">发布内容
    </el-button>
  </div>

  <!--文章功能弹窗-->
  <el-dialog :title="dialogTitle"
             v-model="dialogVisible1"
             width="60%"
             :before-close="handleClose"
  >
    <el-form label-width="80px" label-position="top">
      <el-row :gutter="10"><!--这个gutter就是栅格间隔,这里设置为10-->
        <!--标题输入框-->
        <el-col :span="24">
          <el-form-item label="标题">
            <el-input placeholder="标题不能少于五个字" v-model="saveData.title"></el-input>
          </el-form-item>
        </el-col>
        <!--下拉分类选择框-->
        <el-col :span="24">
          <el-form-item label="分类">
            <el-select placeholder="请选择分类" v-model="popSelect" :disabled="refuseShow">
              <el-option v-for="item in popSelect" :label="item.name" :value="item.id"></el-option>
            </el-select>
          </el-form-item>
        </el-col>

        <!--富文本输入框-->
        <el-col v-if="richTextBox">
          <div style="margin-bottom:5px">
            <label
                style="height:32px;line-height: 32px;font-weight: lighter;font-size: 14px;
            color:#000;">学习内容：</label>
          </div>
          <div style="margin-bottom: 15px;border: 1px solid #ccc">
<!--            <richTextEditor :toolBarConfig="toolBarConfig" content-type='html' v-model="saveData.content"-->
<!--                            style="width: 100%;height: 300px;background-color: white">-->
<!--            </richTextEditor>-->
            <Toolbar
                style="border-bottom: 1px solid #ccc"
                :editor="editorRef"
                :defaultConfig="toolbarConfig"
                mode="default"
            />
            <Editor
                style="height: 500px; overflow-y: hidden;"
                v-model="saveData.content"
                :defaultConfig="editorConfig"
                mode="default"
                @onCreated="handleCreatedEditor"
            />
          </div>
        </el-col>

        <el-col v-if="browseArticle">
          <div style="text-align: center;">{{ saveData.title }}</div>
          <hr>
          <div>{{ saveData.title }}</div>
        </el-col>
      </el-row>

      <el-col v-if="publishButton">
        <el-form-item style="position: relative">
          <!--发布按钮,如果是点击的是浏览,则不会显现-->
          <el-button type="primary" style="position: absolute;right: 0;bottom: -25px">发布
          </el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </el-dialog>


  <!--搜索卡片-->
  <el-card style="margin: 20px;height: 70px;">
    <el-form :inline="true">
      <el-form-item label="搜索">
        <el-input placeholder="请输入资料标题" style="width: 220px;" @keydown.enter.prevent="loadProfileList"
                  v-model="keyWords.title"></el-input>
      </el-form-item>

      <el-form-item label="状态" style="width: 290px;">
        <el-select placeholder="请选择状态" v-model="keyWords.status">
          <el-option label="启用" value="1"></el-option>
          <el-option label="禁用" value="-1"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="分类" style="width: 290px;">
        <el-select placeholder="请选择分类" v-model="keyWords.categoryId">
          <el-option v-for="item in categoryList" :label="item.name" :value="item.id"></el-option>
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="loadProfileList">查询</el-button>
      </el-form-item>
    </el-form>
  </el-card>
  <!--列表框-->
  <el-card style="margin: 20px;">
    <!--这里是列表分类-->
    <el-table :data="tableData">
      <el-table-column label="ID" prop="id" align="center"></el-table-column>
      <el-table-column label="标题" prop="title" align="center">
        <template #default="scope">
          <el-button link type="primary" size="small" @click="showArticle(scope.row.id)">{{ scope.row.title }}
          </el-button>
        </template>
      </el-table-column>
      <el-table-column label="分类" prop="type" align="center" :formatter="formatType"></el-table-column>
      <el-table-column label="状态" prop="status" align="center">
        <template #default="scope">
          <el-switch active-value="1" inactive-value="-1"
                     @change="changeStudyStatus(scope.row.id,scope.row)"
                     v-model="scope.row.status"></el-switch>
        </template>
      </el-table-column>
      <el-table-column label="浏览次数" prop="views" align="center"></el-table-column>
      <el-table-column label="发布人" prop="publisher" align="center"></el-table-column>
      <el-table-column label="发布时间" prop="createTime" align="center"></el-table-column>
      <el-table-column label="操作" align="center">
        <template #default="scope">
          <el-button link type="primary"
                     @click="downloadFile(scope.row.id)">附件下载
          </el-button>
          <!--编辑按钮,区别权限设置还没写,在js当中写判定是否可以点击-->
          <el-button link type="primary"
                     @click="editArticle(scope.row,scope.row.id)" v-if="admin || user.value.name==scope.publisher">编辑
          </el-button>
          <!--删除按钮,管理员权限才可删除,同上-->
          <el-button link type="danger"
                     @click="deleteArticle(scope.row.id)" v-if="admin || user.value.name==scope.publisher">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-card>
</template>

<script setup>
// import { saveAs } from 'file-saver';
import '@wangeditor/editor/dist/css/style.css'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

import {onMounted, ref, shallowRef} from "vue";
import qs from "qs";
import axios from "/src/api/axios";

//定义变量控制文章弹窗是否出现
const dialogVisible1 = ref(false);
//弹窗名
const dialogTitle = ref('发布内容')
//控制编辑标题的变量
const titleVisible = ref(false);
//控制富文本框的变量
const richTextBox = ref(false);
//控制浏览文章的变量
const browseArticle = ref(false);
//控制发布按钮的变量
const publishButton = ref(false);
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

const toolbarConfig = {}
const editorConfig = {placeholder: '请输入内容...'}
const handleCreatedEditor = (editor) => {
  editorRef.value = editor; // 记录 editor 实例，重要！
  saveData.value = {};
}

//控制文章分类的禁用与否
const refuseShow = ref(false);

//列表以及内容分类
const type = ref(10);//默认展示的是文章
//获取当前用户数据的功能
const user = ref(getUser());
//管理员权限先默认为true
const admin = ref(true)

//文章分类列表
const categoryList = ref([]);

const saveData = ref({
  'content': ''
});
//判定当前用户的权限的函数,待定,因为权限现在不明
const isAdmin = (user) => {
  console.log(user)
}
const formatType=(row,column,cellValue,index)=>{
  if(cellValue==1){
    return '娱乐'
  }else if(cellValue==2){
    return '新闻'
  }else if(cellValue==3){
    return '教程'
  }else if(cellValue==4){
    return '规范'
  }else{
    return '未知'
  }
}
//发布按钮功能
const addNews = () => {
  dialogTitle.value = '发布内容';
  titleVisible.value = true;//文章的标题
  dialogVisible1.value = true;//弹窗
  richTextBox.value = true;//富文本框
  publishButton.value = true;//发布按钮
  console.log(publishButton.value);
  refuseShow.value = false;//分类禁用
}

const content = ref('');

//列表数据
const tableData = ref([]);

//搜索框数据,标题,状态,
const keyWords = ref({
  title: '',
  status: '',
  // categoryId: '',//分类id
  type: ''
});
//弹窗分类默认值
const popSelect = ref({
  name: '',
  categoryId: '',
  type: ''
});
//查询资料分类
const loadCategoryList = () => {
  //向后端发送请求,返回来的是分类名称
  axios.get('/v1/study/categoryList', {serviceName: 'studyService'}).then(response => {
    //将返回的数据绑定到tableData中
    categoryList.value = response.data.data;
  })
}
//查询列表
const loadProfileList = () => {
  //这里要将搜索框中的search和type的值装进data中,然后向后端发送请求
  keyWords.value.type = type.value;
  console.log(keyWords.value);
  let data = qs.stringify(keyWords.value);
  console.log(data);
  // 向后端根据搜索框中的内容来发请求拉列表
  axios.get('/v1/study/select?' + data, {serviceName: 'studyService'}).then(response => {
    //将返回的数据绑定到tableData中
    console.log(response);
    tableData.value = response.data.data;
    console.log(tableData.value);
  })
  tableData.value = [];
}

//浏览弹窗
const showArticle = (id) => {
  dialogTitle.value = '内容浏览';
  dialogVisible1.value = true;
  browseArticle.value = true;
  refuseShow.value = true;
  //向后端发送请求,获取到标题,内容,然后绑定到弹窗上

  //绑定数据
  saveData.value.title = tableData.value[0].title;
  saveData.value.content = tableData.value[0].content;
}

//编辑的弹窗
const editArticle = (row, id) => {
  dialogTitle.value = '内容编辑';
  titleVisible.value = true;
  dialogVisible1.value = true;
  richTextBox.value = true;
  publishButton.value = true;
  refuseShow.value = false;
  //向后端发送请求,将资讯的id传过去,然后获取到标题,分类名字,内容,然后绑定到弹窗上
  // axios.get('/v1/study/editSelect?id='+id, {serviceName: 'studyService'}).then(response => {
  //   //这里根据文章id查询对应的文章标题,分类,还有内容,然后绑定到弹窗上
  //
  // })
  //然后将数据传到saveData中,这里将编辑数据绑定到对应的显示栏里
  // saveData.value.title = row.title;
  // saveData.value.content = row.content;
  axios.get('/v1/study/details/' + id, {serviceName: 'studyService'}).then((response) => {
    if (response.data.code === 2000) {
      saveData.value = response.data.data;
      content.value = response.data.data.content;
    }
  })

  // popSelect.value.name = tableData.value[id].name;
  // popSelect.value.categoryId = tableData.value[id].categoryId;
}
//处理弹窗关闭的方法
const handleClose = () => {
  if (confirm('确认要关闭本窗口吗?')) {
    //用户确认关闭后,关闭弹窗
    dialogVisible1.value = false;
    titleVisible.value = false;
    richTextBox.value = false;
    browseArticle.value = false;
    publishButton.value = false;
    saveData.value = {'title': '', 'content': ''};
  }
}

//修改资料状态
const changeStudyStatus = (id, row) => {
  //如果你是管理员,则可以修改状态,否则不能修改状态,修改状态之后,将数据重新加载,并且普通用户无法再浏览

}
//下载功能
const downloadFile = (id) => {
  //假设我这里根据id向后端发送请求了,然后返回来一个response
  //下一步就是将response中的数据打包成一个docx文件,然后下载下来,但是我不知到怎么做了


}
const deleteArticle = (id) => {
  //发送请求,删除数据库中的数据
  loadProfileList();
}

onMounted(() => {
  // isAdmin(user.value.name);
  // loadProfileList();
  loadCategoryList();
  loadProfileList();
})

//富文本编辑框
const toolBarConfig = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],

  [{'header': 1}, {'header': 2}],               // custom button values
  [{'list': 'ordered'}, {'list': 'bullet'}],
  [{'script': 'sub'}, {'script': 'super'}],      // superscript/subscript
  [{'indent': '-1'}, {'indent': '+1'}],          // outdent/indent
  [{'direction': 'rtl'}],                         // text direction

  [{'size': ['small', false, 'large', 'huge']}],  // custom dropdown
  [{'header': [1, 2, 3, 4, 5, 6, false]}],

  [{'color': []}, {'background': []}],          // dropdown with defaults from theme
  [{'font': []}],
  [{'align': []}],

  ['clean']
  // [{'image': ''}], // 添加图片上传功能
];

// 获取 input 元素的引用
const refFileInput = ref(null);//获取input元素
</script>

<style scoped>

</style>